package net.yunxinyong.sign.controller;

import net.yunxinyong.sign.aop.CECException;
import net.yunxinyong.sign.entity.CecOne;
import net.yunxinyong.sign.mapper.SignAdminMapper;
import net.yunxinyong.sign.service.CecOneService;
import net.yunxinyong.sign.service.RecordService;
import net.yunxinyong.sign.service.RegisterStatusService;
import net.yunxinyong.sign.utils.CECResultUtil;
import net.yunxinyong.sign.vo.ResponseVo;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping(value = "one")
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = CECException.class)
public class CecOneController {

    @Autowired
    private CecOneService cecOneService;
    @Autowired
    private SignAdminMapper signAdminMapper;
    @Autowired
    private RegisterStatusService registerStatusService;

    @Autowired
    private RecordService recordService;
    @RequestMapping(value = "update", method = RequestMethod.POST)
    public ResponseVo add(@RequestBody List<CecOne> cecOneList) {
        //获取用户id
        Object principal = SecurityUtils.getSubject().getPrincipal();
        int adminId = Integer.parseInt(principal.toString());
        if (signAdminMapper.selectByPrimaryKey(adminId) != null && signAdminMapper.selectByPrimaryKey(adminId).getState() == 1){
            throw new CECException(402,"当前用户已被禁用");
        }
        cecOneService.insertOrUpdate(cecOneList);
        boolean insert = recordService.insert(adminId, null, null, 12);
        //更新可下载状态
        registerStatusService.updadeDownloadStatus(cecOneList.get(0).getInvId());
        if(!insert){
            throw new CECException(501,"操作失败");
        }
        return CECResultUtil.success("操作成功");
    }

    @RequestMapping(value = "get", method = RequestMethod.GET)
    public ResponseVo get(@RequestParam Integer invId) {
        //获取用户id
        Object principal = SecurityUtils.getSubject().getPrincipal();
        int adminId = Integer.parseInt(principal.toString());
        if (signAdminMapper.selectByPrimaryKey(adminId) != null && signAdminMapper.selectByPrimaryKey(adminId).getState() == 1){
            throw new CECException(402,"当前用户已被禁用");
        }
        List<CecOne> cecOneList = cecOneService.get(invId);
        return CECResultUtil.success("获取成功", cecOneList);
    }
}
